<template>
	<view class="u-form-item" :class="{'u-border-bottom': elBorderBottom, 'u-form-item__border-bottom--error': validateState === 'error' && showError('border-bottom')}">
		<view class="u-form-item__body" :style="{
			flexDirection: elLabelPosition == 'left' ? 'row' : 'column'
		}">
			<!-- 微信小程序中，将一个参数设置空字符串，结果会变成字符串"true" -->
			<view class="u-form-item--left" :style="{
				width: uLabelWidth,
				flex: `0 0 ${uLabelWidth}`,
				marginBottom: elLabelPosition == 'left' ? 0 : '10rpx',
			}">
				<!-- 为了块对齐 -->
				<view class="u-form-item--left__content" v-if="required || leftIcon || label">
					<!-- nvue不支持伪元素before -->
					<text v-if="required" class="u-form-item--left__content--required">*</text>
					<view class="u-form-item--left__content__icon" v-if="leftIcon">
						<u-icon :name="leftIcon" :custom-style="leftIconStyle"></u-icon>
					</view>
					<view class="u-form-item--left__content__label" :style="[elLabelStyle, {
						'justify-content': elLabelAlign == 'left' ? 'flex-start' : elLabelAlign == 'center' ? 'center' : 'flex-end'
					}]">
						{{label}}
					</view>
				</view>
			</view>
			<view class="u-form-item--right u-flex">
				<view class="u-form-item--right__content">
					<view class="u-form-item--right__content__slot ">
						<slot />
					</view>
					<view class="u-form-item--right__content__icon u-flex" v-if="$slots.right || rightIcon">
						<u-icon :custom-style="rightIconStyle" v-if="rightIcon" :name="rightIcon"></u-icon>
						<slot name="right" />
					</view>
				</view>
			</view>
		</view>
		<view class="u-form-item__message" v-if="validateState === 'error' && showError('message')" :style="{
			paddingLeft: elLabelPosition == 'left' ? $u.addUnit(elLabelWidth) : '0',
		}">{{validateMessage}}</view>
	</view>
</template>

<script>
	import Emitter from '../../libs/util/emitter.js';
	import schema from '../../libs/util/async-validator';
	
	schema.warning = function() {};

	

	export default {
		name: 'u-form-item',
		mixins: [Emitter],
		inject: {
			uForm: {
				default () {
					return null
				}
			}
		},
		props: {
			
			label: {
				type: String,
				default: ''
			},
			
			prop: {
				type: String,
				default: ''
			},
			
			borderBottom: {
				type: [String, Boolean],
				default: ''
			},
			
			labelPosition: {
				type: String,
				default: ''
			},
			
			labelWidth: {
				type: [String, Number],
				default: ''
			},
			
			labelStyle: {
				type: Object,
				default () {
					return {}
				}
			},
			
			labelAlign: {
				type: String,
				default: ''
			},
			
			rightIcon: {
				type: String,
				default: ''
			},
			
			leftIcon: {
				type: String,
				default: ''
			},
			
			leftIconStyle: {
				type: Object,
				default () {
					return {}
				}
			},
			
			rightIconStyle: {
				type: Object,
				default () {
					return {}
				}
			},
			
			required: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				initialValue: '', 
				
				validateState: '', 
				validateMessage: '', 
				
				errorType: ['message'],
				fieldValue: '', 
				
				parentData: {
					borderBottom: true,
					labelWidth: 90,
					labelPosition: 'left',
					labelStyle: {},
					labelAlign: 'left',
				}
			};
		},
		watch: {
			validateState(val) {
				this.broadcastInputError();
			},
			
			"uForm.errorType"(val) {
				this.errorType = val;
				this.broadcastInputError();
			},
		},
		computed: {
			
			uLabelWidth() {
				
				return this.elLabelPosition == 'left' ? (this.label === 'true' || this.label === '' ? 'auto' : this.$u.addUnit(this
					.elLabelWidth)) : '100%';
			},
			showError() {
				return type => {
					
					if (this.errorType.indexOf('none') >= 0) return false;
					else if (this.errorType.indexOf(type) >= 0) return true;
					else return false;
				}
			},
			
			elLabelWidth() {
				
				return (this.labelWidth != 0 || this.labelWidth != '') ? this.labelWidth : (this.parentData.labelWidth ? this.parentData
					.labelWidth :
					90);
			},
			
			elLabelStyle() {
				return Object.keys(this.labelStyle).length ? this.labelStyle : (this.parentData.labelStyle ? this.parentData.labelStyle :
					{});
			},
			
			elLabelPosition() {
				return this.labelPosition ? this.labelPosition : (this.parentData.labelPosition ? this.parentData.labelPosition :
					'left');
			},
			
			elLabelAlign() {
				return this.labelAlign ? this.labelAlign : (this.parentData.labelAlign ? this.parentData.labelAlign : 'left');
			},
			
			elBorderBottom() {
				
				return this.borderBottom !== '' ? this.borderBottom : this.parentData.borderBottom ? this.parentData.borderBottom :
					true;
			}
		},
		methods: {
			broadcastInputError() {
				
				this.broadcast('u-input', 'on-form-item-error', this.validateState === 'error' && this.showError('border'));
			},
			
			setRules() {
				let that = this;
				
				
				
				
				
				
				
				
				

				
				this.$on('on-form-blur', that.onFieldBlur);
				
				this.$on('on-form-change', that.onFieldChange);
			},

			
			getRules() {
				
				let rules = this.parent.rules;
				rules = rules ? rules[this.prop] : [];
				
				return [].concat(rules || []);
			},

			
			onFieldBlur() {
				this.validation('blur');
			},

			
			onFieldChange() {
				this.validation('change');
			},

			
			getFilteredRule(triggerType = '') {
				let rules = this.getRules();
				
				if (!triggerType) return rules;
				
				
				
				return rules.filter(res => res.trigger && res.trigger.indexOf(triggerType) !== -1);
			},

			
			validation(trigger, callback = () => {}) {
				
				this.fieldValue = this.parent.model[this.prop];
				
				let rules = this.getFilteredRule(trigger);
				
				
				if (!rules || rules.length === 0) {
					return callback('');
				}
				
				this.validateState = 'validating';
				
				let validator = new schema({
					[this.prop]: rules
				});
				validator.validate({
					[this.prop]: this.fieldValue
				}, {
					firstFields: true
				}, (errors, fields) => {
					
					this.validateState = !errors ? 'success' : 'error';
					this.validateMessage = errors ? errors[0].message : '';
					
					callback(this.validateMessage);
				});
			},

			
			resetField() {
				this.parent.model[this.prop] = this.initialValue;
				
				this.validateState = 'success';
			}
		},

		
		mounted() {
			
			this.parent = this.$u.$parent.call(this, 'u-form');
			if (this.parent) {
				
				Object.keys(this.parentData).map(key => {
					this.parentData[key] = this.parent[key];
				});
				
				if (this.prop) {
					
					this.parent.fields.push(this);
					this.errorType = this.parent.errorType;
					
					this.initialValue = this.fieldValue;
					
					
					this.$nextTick(() => {
						this.setRules();
					})
				}
			}
		},

		
		beforeDestroy() {
			
			if (this.parent && this.prop) {
				this.parent.fields.map((item, index) => {
					if (item === this) this.parent.fields.splice(index, 1);
				})
			}
		},
	};
</script>

<style lang="scss" scoped>
	@import "../../libs/css/style.components.scss";

	.u-form-item {
		@include vue-flex;
		
		padding: 20rpx 0;
		font-size: 28rpx;
		color: $u-main-color;
		box-sizing: border-box;
		line-height: $u-form-item-height;
		flex-direction: column;

		&__border-bottom--error:after {
			border-color: $u-type-error;
		}

		&__body {
			@include vue-flex;
		}

		&--left {
			@include vue-flex;
			align-items: center;

			&__content {
				position: relative;
				@include vue-flex;
				align-items: center;
				padding-right: 10rpx;
				flex: 1;

				&__icon {
					margin-right: 8rpx;
				}

				&--required {
					position: absolute;
					left: -16rpx;
					vertical-align: middle;
					color: $u-type-error;
					padding-top: 6rpx;
				}

				&__label {
					@include vue-flex;
					align-items: center;
					flex: 1;
				}
			}
		}

		&--right {
			flex: 1;

			&__content {
				@include vue-flex;
				align-items: center;
				flex: 1;

				&__slot {
					flex: 1;
					/* #ifndef MP */
					@include vue-flex;
					align-items: center;
					/* #endif */
				}

				&__icon {
					margin-left: 10rpx;
					color: $u-light-color;
					font-size: 30rpx;
				}
			}
		}

		&__message {
			font-size: 24rpx;
			line-height: 24rpx;
			color: $u-type-error;
			margin-top: 12rpx;
		}
	}
</style>
